package io.renren.modules.sys.controller;


import io.renren.common.exception.RRException;
import io.renren.modules.sys.service.SysConfigService;
import io.renren.modules.sys.util.ResponseUtil;
import io.renren.modules.sys.util.StringUtil;
import io.renren.modules.sys.util.Word2Html;
import io.renren.modules.sys.util.ExcelUtil;
import net.sf.json.JSONObject;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.*;
import java.util.ArrayList;

import static io.renren.modules.sys.util.PdfUtil.*;


/**
 * 文件对比Controller层
 *
 * @author chenyu
 * @date 2018/07/23
 */
@Controller
@RequestMapping("sys/view")
public class WordViewController {
    private static Logger logger = LoggerFactory.getLogger(WordViewController.class);

    @Resource
    private SysConfigService sysConfigService;


    @RequestMapping("/compWordurl")
    public String listToQxurl(@RequestParam(value = "path", required = false) String path, HttpServletRequest request, HttpServletResponse response) throws Exception {
        int num = path.indexOf(".");
        if (path.substring(num + 1).equals("xls") || path.substring(num + 1).equals("xlsx")) {
            File file = new File(path);
            Workbook w = ExcelUtil.readFile(file);
            ArrayList<String[]> list = ExcelUtil.readSheetData(w, 0);
            if (list != null) {
                String content1 = "<table class='table table-bordered' id='tables'>";
                for (String[] s : list) {
                    content1 += "<tr>";
                    for (String s_byte : s) {
                        content1 += "<td>" + s_byte + "</td>";
                    }
                    content1 += "</tr>";
                }
                content1 += "</table>";
                JSONObject result = new JSONObject();
                result.put("html1", content1);
                ResponseUtil.write(response, result);
            }

            return null;
        }

        JSONObject result = new JSONObject();
        String tempPath = getHtml(path);
        if (StringUtil.isEmpty(tempPath)) {
            result.put("errMsg", "请选择word文档，后缀名doc或者docx");
            ResponseUtil.write(response, result);
            return null;
        }
        String content1 = "";
        try {
            content1 = getContent(tempPath, request);
        } catch (Exception e) {
            result.put("errMsg", "对比的附件已损坏");
            ResponseUtil.write(response, result);
            return null;
        }

        result.put("html1", content1);
        logger.info(content1);
        ResponseUtil.write(response, result);
        return null;
    }

    private String getContent(String tempPath, HttpServletRequest request) throws IOException {
        String ip = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
//        //创建一个FileReader
        InputStreamReader f = null;
        BufferedReader bw = null;
        String line = null;
        String numVal = "";
        File file = new File(tempPath);
        try {
            f = new InputStreamReader(new FileInputStream(file), "UTF-8");//
            bw = new BufferedReader(f);
            //读出一行数据 或者使用for循环都区全部内容
            while ((line = bw.readLine()) != null) {
                //替换图片src地址
                line = line.replaceAll("\\\\", "/");
                StringBuilder stringBuilder2 = new StringBuilder(line);
                int index = stringBuilder2.indexOf("<img src=");
                if (index > 0) {
                    stringBuilder2.insert(index + 10, ip + "/sys/tghfile/previewIMGpath?path=");
                    line = stringBuilder2.toString();
                }

                numVal = numVal + line;

            }
            numVal = numVal.replaceAll("<html>", "");
            numVal = numVal.replaceAll("</html>", "");
            numVal = numVal.replaceAll("<head>", "");
            numVal = numVal.replaceAll("</head>", "");
            numVal = numVal.replaceAll("<body>", "");
            numVal = numVal.replaceAll("</body>", "");

            //  numVal = numVal.replaceAll("img src=\"","");
//            picUrlEncode(numVal);
            //一定要关闭文件流
        } finally {
            if (f != null) {
                f.close();
            }
            if (bw != null) {
                bw.close();
            }
            //删除临时文件
            File tempFIle = new File(tempPath);
            if (tempFIle.exists()) {
                tempFIle.delete();
            }
        }
        return numVal;


    }

    private static String previewExcel() throws UnsupportedEncodingException {

        return null;
    }

    /**
     * 生成html文件
     *
     * @param path
     * @return
     * @throws ParserConfigurationException
     * @throws TransformerException
     * @throws IOException
     */
    private static String getHtml(String path) throws ParserConfigurationException, TransformerException, IOException {
        String tempPath = "";
        if (path.toLowerCase().indexOf(".docx") > 0) {
            tempPath = getTempFileName(path.toLowerCase(), ".docx");
            Word2Html.docx2Html(path, tempPath);
        } else if (path.toLowerCase().indexOf(".doc") > 0) {
            tempPath = getTempFileName(path.toLowerCase(), ".doc");
            Word2Html.doc2Html(path, tempPath);
        }
        return tempPath;
    }


    /**
     * 获取临时文件
     *
     * @param path 原路径
     * @param pre  后缀
     * @return
     */
    private static String getTempFileName(String path, String pre) {
        path = path.replaceAll(pre, ".html");
        File file = new File(path);
        if (file.exists()) {
            logger.info(path + "已经存在,删除临时文件");
            file.delete();
            logger.info("删除成功");
        }
        return path;
    }


    private static String imgHtml(XWPFDocument xwpfDocument, String blipID) {
        XWPFPictureData pictureData = xwpfDocument.getPictureDataByID(blipID);
        String imageName = pictureData.getFileName();
        String newfilename = System.currentTimeMillis() + imageName;
        byte[] bytev = pictureData.getData();
        try (FileOutputStream fos = new FileOutputStream("E:/" + newfilename);) {
            fos.write(bytev);// 此处保存图片后，变成可访问的http然后用<img>标签包裹
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "<img src='/usr/test_zgzx/zgzx-admin/zgzxfile'>";
    }



    /**
     * word excel  ppt文件预览转pdf
     *
     * @param path     path
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/compWordpdfs")
    public void listToQxss(@RequestParam("path") String path, HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/pdf");
        File files = new File(path);
        String fileName = files.getName();
        String paths = sysConfigService.getValue("saveFile");
        String separator = File.separator;
        Integer index = fileName.lastIndexOf(".");
        String suffix = fileName.substring(index).toLowerCase();
        String pdfPath = fileName.replace(suffix, "preview") + ".pdf";
        File filess = new File(paths + separator + separator + "preview" + separator);
        if (!filess.exists()) {
            filess.mkdirs();
        }
        pdfPath = paths + separator + separator + "preview" + separator + pdfPath;
        File file = new File(pdfPath);
        boolean is = false;
        try {
            if (suffix.equals(".doc") || suffix.equals(".docx")) {
                is = doc2pdf(path, pdfPath);
            } else if (suffix.equals(".xls") || suffix.equals(".xlsx")) {
                is = excel2pdf(path, pdfPath);
            } else if (suffix.equals(".pptx") || suffix.equals(".ppt")) {
                is = ppt2pdf(path, pdfPath);
            }
            if (!is) {
                return;
            }
        } catch (OutOfMemoryError e) {
            System.out.println(e.getMessage());
            throw new RRException("文件中图片过大预览失败，请下载后查看！");
        }
        //读取文件(缓存字节流)
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(pdfPath)));
        //写入相应的文件
        OutputStream out = response.getOutputStream();
        //读取数据
        //一次性取多少字节
        byte[] bytes = new byte[1024];
        //接受读取的内容(n就代表的相关数据，只不过是数字的形式)
        int n = -1;
        //循环取出数据
        while ((n = in.read(bytes, 0, bytes.length)) != -1) {
            //写入相关文件
            out.write(bytes, 0, n);
        }
        //清楚缓存
        out.flush();
        //关闭流
        in.close();
        out.close();
        file.delete();
    }


}
